'''
    ------------------------------
    这是项目的主文件。它将用于运行项目。
    ------------------------------
'''
import asyncio
# 导入模块
import configparser as config
import logging
import os
import shutil
import sys
from PageAnalyse.ccgpAnalyse import ccgpcrawler
from PageAnalyse.ztbAnalyse import ztbcrawler
from settingObj.settings import settings
from utils.sheettools import sheetprocess, uniformStyle, dataAppendTestCase
from log.clog import logger

# 读取配置文件 settingObj.ini
try:
    config = config.ConfigParser()
    config.read('./config.ini', encoding='utf-8')
except Exception as e:
    logger.error('没有找到配置文件', e)

# 读取配置文件中的配置
try:
    output_path = config.get('PATH', 'OUTPUT_PATH')
    global_match_path = config.getboolean('SETTING', 'GLOBAL_MATCH')
    all_data = config.getboolean('SETTING', 'ALL_DATA')
    output_fIle_name = config.get('FILENAME', 'FILENAME')
    start_time = config.get('FILENAME', 'STARTDATE')
    end_time = config.get('FILENAME', 'ENDDATE')
    sleep_time = config.getfloat('OTHER', 'SLEEP_TIME')
    COPY_PATH = output_path + 'COPY'
except Exception as e:
    logger.error('配置文件参数读取失败', e)

from datetime import datetime

# 获取今天的日期
today = datetime.now()

print('---------------------------------')
print('配置文件读取成功:')
print(f'输出路径 output_path:      -->{output_path}')
print('全局模糊搜索 global_match_path:-->', global_match_path)
print('输出文件名 output_fIle_name: -->', output_fIle_name)
print('全量数据 oall_data: -->', all_data)
print('开始时间 start_time: -->', start_time)
print('结束时间 end_time: -->', end_time)
print('---------------------------------')

'''
    判断输出路径是否存在,并依靠 settingObj.ini 文件相关配置创建文件
    生成同路径及备份路径
'''
try:
    if not os.path.exists(output_path):
        os.makedirs(output_path)
        print('目录不存在,创建成功')
    filepath = os.path.join(output_path, output_fIle_name)
except Exception as e:
    logger.error('目录不存在,创建失败', e)

# 加载文件并利用openpyxl将其生成为 worksheet 对象
try:
    import openpyxl as op
except Exception as e:
    logger.error('没有对应的 openpyxl 库文件')

logger.info('开始运行项目')
# 加载 excel 处理模块,并进行部分预备处理
work = sheetprocess(filepath=filepath)
# 创建一个新的 excel 文件
work.createWorkBook()
# 打开并加载一个 excel 文件
excel = op.load_workbook(filepath)

# 加载全局配置
config = settings(output_path=output_path,
                  global_match_path=global_match_path,
                  output_fIle_name=output_fIle_name,
                  filepath=filepath,
                  all_data=all_data,
                  excel=excel,
                  start_time=start_time,
                  end_time=end_time,
                  sleep_time=sleep_time)

import time
# 使用连接进行操作（示例：查询数据库）
# 官方示例

# cursor.execute("SELECT * FROM your_table")
# rows = cursor.fetchall()
# for row in rows:
#     print(row)

# 记录开始时间
start_time = time.time()
# 依次对招标数据进行爬取[ 主要业务逻辑 ]
# 对 ccgp 网站进行爬虫处理 传入相关数据参数()
ccgpStartTime = time.time()

try:
    logger.info('ccgp 数据爬虫开始')
    ccgp = ccgpcrawler(config)
    asyncio.run(ccgp.threadMain())
except Exception as e:
    logger.error('ccgp 数据爬虫出现异常', e)
except KeyboardInterrupt as keyerr:
    logger.error('ccgp 数据爬虫被终止')
finally:
    logger.info('ccgp 数据爬虫完成')
ccgpEndTime = time.time()

# 对 ztb 网站进行爬虫处理 传入相关数据参数()
ztbStartTime = time.time()
try:
    logger.info('ztb 数据爬虫开始')
    ztb = ztbcrawler(config)
    asyncio.run(ztb.threadMain())
except Exception as e:
    logger.error('ztb 数据爬虫出现异常', e)
except KeyboardInterrupt as e:
    logger.error('ztb 数据爬虫被终止')
finally:
    logger.info('ztb 数据爬虫完成')
ztbEndTime = time.time()

# 统一格式
# dataAppendTestCase(filepath)
try:
    logger.info('统一格式开始')
    uniformStyle(filepath)
except Exception as e:
    logging.exception(e)
finally:
    print('统一格式完成')

try:
    # 复制文件并重命名
    target_file_name = '备份' + output_fIle_name
    target_filepath = os.path.join(COPY_PATH, target_file_name)
    shutil.copy(filepath, target_filepath)
    logger.info('文件备份成功')
except Exception as e:
    logger.error('文件复制失败', e)

# 记录结束时间
end_time = time.time()
print(f'\n总共耗时: {round(end_time - start_time)} 秒')
print(f'ccgp网站耗时: {round(ccgpEndTime - ccgpStartTime)} 秒')
print(f'ztb网站耗时: {round(ztbEndTime - ztbStartTime)} 秒')

'''
    关闭 PL/SQL 数据库连接通道
'''

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
from email.mime.text import MIMEText

# 邮件发送方和接收方信息
sender = 'asdfzxcvqwer123a@126.com'
receiver1 = 'superces@126.com'
# receiver2 = '404480276@qq.com'
# receiver3 = 'superces@126.com'
password = 'HRBRRZQTAXWIKKHM'  # 126邮箱的SMTP服务密码
smtpserver = 'smtp.126.com'

# 创建一个带附件的邮件消息对象
msg = MIMEMultipart()
msg['From'] = sender
msg['Subject'] = "招标数据"

# 邮件正文内容
body = "招标数据详见附件"
msg.attach(MIMEText(body, 'plain'))

# 附件文件名和路径
filename = filepath
attachment = open(filename, "rb")

# 添加附件到邮件消息中
part = MIMEBase('application', 'vnd.openxmlformats-officedocument.spreadsheetml.sheet')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % filename)

# 将附件添加到邮件中
msg.attach(part)

try:
    smtp = smtplib.SMTP()
    smtp.connect(smtpserver, 25)  # 连接SMTP服务器，25为SMTP端口号
    smtp.login(sender, password)  # 登录邮箱，注意这里是SMTP服务密码
    smtp.sendmail(sender, receiver1, msg.as_string())  # 发送邮件
    # smtp.sendmail(sender, receiver2, msg.as_string())  # 发送邮件
    smtp.quit()
    print("邮件发送成功！")
except smtplib.SMTPException as e:
    print("Error: 无法发送邮件", e)
finally:
    attachment.close()
